const express = require('express');
const app = express();
const fs = require('fs');
const bodyParser = require('body-parser');
const multer = require('multer');

app.use(express.static('public'));
app.use(bodyParser.urlencoded({extended:false}));
app.use(multer({ dest: '/tmp/'}).array('file'));

app.get('/index.html',(req,res) => {
    res.sendFile(__dirname + '/' + 'index.html');
})

app.post('/fileUpload',(req,res) => {
    console.log(req.files[0]);  //上传文件信息

    let des_file = __dirname + '/' + req.files[0].originalname;
    fs.readFile(req.files[0].path,(err,data) => {
        fs.writeFile(des_file,data,(err) => {
            if(err){
                console.error(err);
            }
            else{
                response = {
                    message:'File uploaded successfully',
                    filename:req.files[0].originalname
                };
            }
            console.log(response);
            res.end(JSON.stringify(response));
        })
    })
})

var server = app.listen(8081, () => {
  var host = server.address().address
  var port = server.address().port
  console.log("应用实例，访问地址为 http://:", host, port)
})
